// eslint-disable-next-line no-unused-vars
import router, { asyncRoutes, constantRoutes } from '@/router/index.js'
import store from '@/store/index.js'

// 路由守卫
router.beforeEach(async(to, from, next) => {
  // 定义一个白名单
  const whileList = ['/login', '/404']
  if (store.state.user.token) {
  // 如果已经登录
    // 如果已经登录.又访问登录页面, 则跳转到首页
    if (to.path === '/login') {
      return next('/')
    } else {
      // 查看是否含有用户信息
      if (!store.getters.userId) {
        /*
        // 简化写法
        // 1.获取标识
        const { roles: { menus }} = await store.dispatch('user/getUserInfo')
        console.log(menus)
        // 2. 过滤路由
        const filterRouters = asyncRoutes.filter(t => menus.includes(t.name))
        // 3.添加动态路由 路由的跳转
        // 通过动态路由添加的,不会影响 router.option.routes
        console.log(filterRouters)
        router.addRoutes(filterRouters)
        // 4.解决菜单显示问题
        router.options.routes = [
          ...constantRoutes,
          ...filterRouters,
          // 404 page must be placed at the end !!!
          { path: '*', redirect: '/404', hidden: true }
        ]
        // 5. 解决刷新404
        return next(to.path)
        */

        // 标准写法
        // 1.获取标识
        const { roles: { menus }} = await store.dispatch('user/getUserInfo')
        console.log(menus)
        // 2.过滤动态路由
        const fliterRoutes = await store.dispatch('permission/onFilterRoutes', menus)
        console.log(fliterRoutes)
        // 3.添加动态路由 路由的实际跳转
        router.addRoutes([
          ...fliterRoutes,
          // 404 page must be placed at the end !!!
          { path: '*', redirect: '/404', hidden: true }
        ])
        return next(to.path)
      }
    }
    next()
  } else if (whileList.includes(to.path)) {
    // 如果路径在白名单中
    next()
  } else {
    next('/login')
  }
})
